<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\User;

/**
 * 班级学生管理
 *
 * @icon fa fa-circle-o
 */
class SchoolCalssUser extends Backend
{

    /**
     * SchoolCalssUser模型对象
     * @var \app\admin\model\SchoolCalssUser
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SchoolCalssUser;
        $this->assignconfig('group_id',$this->auth->getGroupIds()[0]);
        $this->assignconfig('mobiles',$this->auth->check('school_calss_user/mobile'));
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $class_id = $this->request->request('class_id', 0);
            $class_where = [];
            if ($class_id) {
                $class_where['class_id'] = $class_id;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($class_where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($class_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id', 'nickname', 'mobile', 'total_class_hour', 'use_class_hour', 'createtime', 'status', 'duty_time']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $class_id = $this->request->request('class_id', 0);
        $this->assignconfig('class_id', $class_id);
        return $this->view->fetch();
    }

    /**
     * 添加学生
     * @return string
     * @throws PDOException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {


        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            $r_time = $params['r_time'];


            $user_ids = explode(',', $params['user_id']);
            //查找班级
            $calss_name = db('school_class')
                ->where('id', $params['class_id'])
                ->find();
            //查找班级科目
            $class_subject = db('school_class_subject')
                ->where('class_id', $params['class_id'])
                ->find();
            //联表查询科目表。取出科目表课费时。
            $cost = db('school_class_subject')
                ->alias('a')
                ->join('ed_school_subject b', 'b.id = a.subject_id')
                ->where('a.class_id', $params['class_id'])
                ->sum('b.cost');

            //判断
            if (isset($params['class_discount'])) {
                if ($params['class_discount']) {
                    if ($calss_name['class_discount'] == '1') {
                        $cost = $calss_name['price'];
                    } elseif ($calss_name['class_discount'] == '2') {
                        $cost = $cost * ($calss_name['discount'] / 100);
                    }
                }
            }
            $school_class_subject_schedule = db('school_class_subject_schedule')->where('class_id', $params['class_id'])->where('status', '1')->where('id', 'notin', $params['subject_schedule_id'])->select();

            $data = [];
            $dataLog = [];
            $common_user = new User();
            $total_class_hour = $class_subject['total_class_hour'] - $class_subject['use_class_hour'];
            foreach ($user_ids as $k => $v) {
                $class_subject = db('school_class_subject')->where('class_id', $params['class_id'])->find();
                $user_info = db('user')->where('id', $v)->find();

                db('user')->where('id', $user_info['id'])->update(['admin_id' => $calss_name['admin_id']]);
                //添加班级学生公用参数

                $cost_one = $calss_name['class_discount'] == '1' ? $cost / $class_subject['total_class_hour'] * ($class_subject['total_class_hour'] - $class_subject['use_class_hour']) : $cost;

                $data[$k] = [
                    'cost' => $cost_one,
                    'user_id' => $user_info['id'],
                    'class_id' => $params['class_id'],
                    'nickname' => $user_info['nickname'],
                    'mobile' => $user_info['mobile'],
                    'createtime' => time(),
                    'duty_time' => strtotime($r_time),
                    'class_discount' => $calss_name['class_discount']
                ];

                if (strtotime($r_time) > $calss_name['start_time']) {


                    $data[$k]['total_class_hour'] = $total_class_hour;

                    if ($calss_name['class_discount'] == '3') {
                        if ($user_info['discount_amount'] > 0) {
                            if ($user_info['discount_amount'] >= $total_class_hour) {
                                $data[$k]['quan'] = $total_class_hour;
                                $total_class_hour = 0;

                                db('user')->where('id', $user_info['id'])->setDec('discount_amount', $data[$k]['quan']);

                                $dataLog[] = [
                                    'admin_id' => $this->auth->id,
                                    'user_id' => $user_info['id'],
                                    'create_time' => time(),
                                    'content' => '加入班级' . $calss_name['class_name'] . '，扣除优惠课时' . $data[$k]['quan'],
                                ];
                            } else {
                                $total_class_hour = $total_class_hour - $user_info['discount_amount'];
                                $data[$k]['quan'] = $user_info['discount_amount'];

                                db('user')->where('id', $user_info['id'])->setDec('discount_amount', $data[$k]['quan']);

                                $dataLog[] = [
                                    'admin_id' => $this->auth->id,
                                    'user_id' => $user_info['id'],
                                    'create_time' => time(),
                                    'content' => '加入班级' . $calss_name['class_name'] . '，扣除优惠课时' . $data[$k]['quan'],
                                ];
                            }
                        }
                    }
                    //if(){}
                    $momey = $calss_name['class_discount'] == '1' ? $cost / $class_subject['total_class_hour'] * ($class_subject['total_class_hour'] - $class_subject['use_class_hour']) : $total_class_hour * $cost;
                    $common_user->money(-$momey, $user_info['id'], '加入班级扣费');
                    $dataLog[] = [
                        'admin_id' => $this->auth->id,
                        'user_id' => $user_info['id'],
                        'create_time' => time(),
                        'content' => '插入班级' . $calss_name['class_name'] . '，扣除余额' . $momey . ',新增课时' . $data[$k]['total_class_hour'] . '课时',
                    ];
                } else {
                    $data[$k]['total_class_hour'] = $class_subject['total_class_hour'];
                    $data[$k]['use_class_hour'] = count($school_class_subject_schedule);
                    $total_class_hours = $class_subject['total_class_hour'];
                    if ($calss_name['class_discount'] == '3') {
                        //优惠课时逻辑
                        if ($user_info['discount_amount'] > 0) {
                            if ($user_info['discount_amount'] >= $class_subject['total_class_hour']) {
                                $data[$k]['quan'] = $class_subject['total_class_hour'];
                                $class_subject['total_class_hour'] = 0;

                                db('user')->where('id', $user_info['id'])->setDec('discount_amount', $data[$k]['quan']);

                                $dataLog[] = [
                                    'admin_id' => $this->auth->id,
                                    'user_id' => $user_info['id'],
                                    'create_time' => time(),
                                    'content' => '加入班级' . $calss_name['class_name'] . '，扣除优惠课时' . $data[$k]['quan'],
                                ];
                            } else {
                                $total_class_hours = $class_subject['total_class_hour'];
                                $class_subject['total_class_hour'] = $class_subject['total_class_hour'] - $user_info['discount_amount'];
                                $data[$k]['quan'] = $user_info['discount_amount'];

                                db('user')->where('id', $user_info['id'])->setDec('discount_amount', $data[$k]['quan']);

                                $dataLog[] = [
                                    'admin_id' => $this->auth->id,
                                    'user_id' => $user_info['id'],
                                    'create_time' => time(),
                                    'content' => '加入班级' . $calss_name['class_name'] . '，扣除优惠课时' . $data[$k]['quan'],
                                ];
                            }
                        }else{
                            $data[$k]['quan'] = 0;
                        }
                    }

                    $momey = $calss_name['class_discount'] == '1' ? $cost : $class_subject['total_class_hour'] * $cost;
                    $common_user->money(-$momey, $user_info['id'], '加入班级扣费');
                    if($momey){
                        $dataLog[] = [
                            'admin_id' => $this->auth->id,
                            'user_id' => $user_info['id'],
                            'create_time' => time(),
                            'content' => '加入班级' . $calss_name['class_name'] . '，扣除余额' . $momey . ',新增课时' . $total_class_hours . '课时',
                        ];
                    }
                    if (count($school_class_subject_schedule)) {
                        $dataLog[] = [
                            'admin_id' => $this->auth->id,
                            'user_id' => $user_info['id'],
                            'create_time' => time(),
                            'content' => '已上课' . count($school_class_subject_schedule) . '课时，结算-' . count($school_class_subject_schedule) . '课时',
                        ];
                    }
                }

            }
            $SchoolUserLog = model('SchoolUserLog');
            $SchoolUserLog->insertAll($dataLog);
            $this->model->insertAll($data);
            $this->success('操作成功');
        }
        $class = $this->request->request('class_id', 0);
        $class_user_info_list = $this->model->where('class_id', $class)->select();
        $class_info = db('school_class')->where('id', $class)->find();
        $class_user_info = array_column($class_user_info_list, 'user_id');
        $user_ids = implode(',', $class_user_info);
        $this->assign('user_ids', $user_ids);
        $this->assign('class_id', $class);
        $this->assign('class_info', $class_info);
        return $this->view->fetch();
    }

    /**
     * 退班
     */
    public function leave_work()
    {
        $class_user_id = input('ids');

        $type = $this->request->request('type');
        $value = $this->request->request('value', 0);

        $calss_user_info = db('school_calss_user')->where('id', $class_user_id)->find();
        //print_r($calss_user_info);
        if ($calss_user_info['status'] == 0) {
            db('school_calss_user')->where('id', $class_user_id)->update(['status' => '2', 'work_time' => time()]);
            $money = ($calss_user_info['total_class_hour'] - $calss_user_info['use_class_hour']) * $calss_user_info['cost'];

            if ($calss_user_info['class_discount'] == 1) {
                $money = $calss_user_info['cost'] / $calss_user_info['total_class_hour'] * ($calss_user_info['total_class_hour'] - $calss_user_info['use_class_hour']);
            } else if ($calss_user_info['class_discount'] == 3) {
                if ($calss_user_info['use_class_hour'] < $calss_user_info['quan']) {
                    $shengyu = $calss_user_info['quan'] - $calss_user_info['use_class_hour'];
                    db('user')->where('id', $calss_user_info['user_id'])->setInc('discount_amount', $shengyu);
                    $dataLoss = [
                        'admin_id' => $this->auth->id,
                        'user_id' => $calss_user_info['user_id'],
                        'create_time' => time(),
                        'content' => '退班，退回费用优惠课时' . $shengyu,
                    ];
                    db('SchoolUserLog')->insert($dataLoss);
                    $money = $calss_user_info['cost'] * ($calss_user_info['total_class_hour'] - $calss_user_info['use_class_hour'] - $shengyu);
                }
            }
            $common_user = new User();

            $common_user->money($money, $calss_user_info['user_id'], '退班');
            db('user')->where('id', $calss_user_info['user_id'])->update(['admin_id' => $this->auth->id]);

            $dataLog = [
                'admin_id' => $this->auth->id,
                'user_id' => $calss_user_info['user_id'],
                'create_time' => time(),
                'content' => '退班，退回费用' . $money . '元'
            ];
            db('SchoolUserLog')->insert($dataLog);
            $this->success('退出成功');
        } else {
            $this->error('状态不正确');
        }

    }
}
